<template>
  <div class='box-wrap-total'>
    <section class='box-operation'>
      <div class="box-search">
        <div class='form-group-enquire'>
          <el-select v-model="searchData.id" placeholder="全部国家" clearable filterable>
            <el-option :value= row.id v-for="row in CountryList" :label="'('+ row.short_name+')'+row.full_name" :key= row.id ><span style="float:left;color:#FF0000">({{row.short_name}})&nbsp;</span>{{row.full_name}}</el-option>
          </el-select>
        </div>                      
          
        <div class='form-group-img' @click='onSearchGetList()'><img src="../../assets/images/peach-svg/Frame 23.svg"></div>
        <!-- <div class='form-group-addimg' @click='editInfo(1,{})'><img src="../../assets/images/peach-svg/add.svg"></div> -->
      </div>
    </section>
    <LibVxeTable class="staticData" :stripe="stripe" :tableColumns="tableColumns" border="none" :tableData="list" :slotHeader="slotHeader" :PageObj="{total:totalCnt,currentPage:searchData.page_index,pageSize:searchData.page_size}"  @onPageChange="onChangePageSize" resizable></LibVxeTable>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import utils from "../../commons/utils";
import {commonMixin} from "../../components/ViewInitMixin" //每一个文件都要包含这个
import {TimePicker} from "iview"
import SearchUser from "../searchUser"
import Request from "../../commons/Request"
import bus from "../../commons/EventBus"
export default {
  name: "addUserDetailView",  //!!这块一定要注意，每一个文件都根据资源path来命名
  components:{TimePicker,SearchUser},
  mixins:[commonMixin],
  data() {
    return {
      stripe:false,      
      statuslist: [{id:1,name:'启用'},{id:2,name:'禁用'}],
      modal:false,
      searchDate:"",
      searchTime:[utils.dateFormat(0,"HH")+"00",utils.dateFormat(0,"HH")+"00"],
      searchData:{
        // account:"",
        page_index:1,
        page_size:30,
        id:"",
      },
      versionsList:[{Id:-1,Name:'全部版本'},{Id:1,Name:'v1'},{Id:2,Name:'v2'}],
      mnoList:{},
      provinceList:{},
      list:[],
      totalCnt:0,
      info:{},
      channelList:[],
      cityList:[],
      cityInfo:[-1],
      partnerList:[],
      ChannelList:[],
      QdsPartnerList:[],
      QdsPartnerObj:{},
      BusinessList:[],
      BusinessObj:{},
      cityObj:{},
      brandObj:{},
      brandObjCh:{},
      formPopIndex:0,
      roles:[],
      leaders:[],
      roleObj:{},
      CountryList:[],
      leaderlist:[],
      tableColumns:[
        {
          title: "序号",
          field: "id",
          align: 'center',
        },
        {
          title: "国家",
          field: "full_name",
          align: 'center',
        },
        {
          title: "简称",
          field: "short_name",
          align: 'center',
        },
        {
          title: "区号",
          field: "area_code",
          align: 'center',
        },
        {
          title: "号码位数",
          field: "number_bit_count",
          align: 'center',
        },
        {
          title: "状态",
          field: "status",
          align: 'center',
          slots: {
                default: ({row},h) => {
                    let disabled = false;
                    if(this.Perm.add){
                        disabled = false;
                    }
                    return [h("iSwitch",
                            {
                                props: {
                                value:(1 & row.status)==1?true:false,
                                disabled:disabled,
                                size:"large",
                                },
                                on: {
                                'on-change': (value) => {
                                    let info = {"id":row.id};
                                    value==true?this.handleType = 3:this.handleType = 4;
                                    this.updateInfo(info);
                                }
                                }
                            },
                            [
                                h('span', {
                                slot: 'open',
                                domProps: {
                                    innerHTML: '启用'
                                }
                                }),
                                h('span', {
                                slot: 'close',
                                domProps: {
                                    innerHTML: '禁用'
                                }
                                })
                            ]
                    )];
                }
            }
          // slots: {
          //     default: ({row},h) => {
          //        if(row.status==1){
          //          return [h("p","启用")]
          //       }else if(row.status==2){
          //         return [h("p","禁用")]
          //       }
          //   }
          // }
        },
         {
          title: "创建时间",
          field: "create_at",
          align: 'center',
          slots:{
            default:({row},h) =>{
              if(row.create_at==0){
                return [h("div",'-')]
              }else
              return [h("div",utils.dateFormat(row.create_at,"yyyy-MM-dd HH:mm:ss"))]
            }
          }
        },
        {
          title: "创建人",
          field: "creator_name",
          align: 'center',
        },
        {
          title: "操作",
          field: "action",        
          width: 150,
          align: "center",
          slots:{
            default: ({row},h) => {
              return this.$AutoFun(()=>{
              let hButton = [];

                hButton.push(h(
                    "div",
                    {
                      class:"two",
                      on: {
                        click: () => {
                          this.editInfo(2,row);
                        }
                      }
                    },
                  ));
                hButton.push(
                  h(
                    "div",
                    {
                      class:"three",
                      on: {
                        click: () => {
                          this.sureDel(row,-1);
                        }
                      }
                    },
                  )
                );
              return hButton;
            });
            }
          }
        }
      ],
      format: {  
        full_name:{
          labelName: "国家名称",
          labelType: "text",      
          placeholder:"请输入国家名称"
        },
        short_name:{
          labelName: "简称",
          labelType: "text",     
          placeholder:"请输入简称"          
        },
        area_code:{
          labelName: "区号",
          labelType: "text",        
          placeholder:"请输入区号" 
        },
        number_bit_count:{
          labelName: "号码位数",
          labelType: "text",   
          placeholder:"请输入号码位数"  
        },
        disable_sieve_list:{
          labelName: "禁用筛选",
          labelType: "select",    
          labelValue:[], 
          labelMultiple: true,
          placeholder:"请选择数据",  
        },               
      },     
      ruleValidate: {
        full_name: [{ required: true,message: "国家名称不能为空", trigger: "blur" }],
        short_name:[{ required: true,message: "简称不能为空", trigger: "blur" }],
        area_code:[{ required: true,message: "区号不能为空", trigger: "blur" }],
        // number_bit_count:[{ required: true,message: "号码位数不能为空", trigger: "blur" }],
      },      
      dateOptions:{
        disabledDate(date){
          return date && date.valueOf() > Date.now();
        },

      },
    };
  },
  computed: {
            ...mapGetters(["UserInfo"]),              
        },
  methods: {
    async initView(isMounted){
      if(isMounted){
        await this.getList();
        await this.initSearchData();
      }
    },
    async initSearchData() { 
      let leaders = await this.RequestPost("queryCountries_list");
      //国家列表
      if(leaders.data!=null){
        leaders.data.list.forEach((item) => {
          this.CountryList.push(item)
          this.$set(this.roleObj,item.role_id,item.role_name)
        })       
      } 
      //业务类型下拉框接口
      let res = await Request.post('customer/businessType','query_list')
      let data = res.data.list
      if(res.code==0 && data.length != 0 && data!=null){
        data.forEach(item =>{
          this.leaderlist.push({id:item.id,name:item.desc+"("+item.name+")"})
        })
        this.format.disable_sieve_list.labelValue=this.leaderlist
      } 
    },
    onSearchGetList(){
      this.searchData.page_index =1;
      this.getList();
    },
    async getList(){
            //  bus.$emit('sub',this.list)    
      utils.showLoading()  
      let res = await this.RequestPost("query_list",this.searchData); 
      if(res.code==0 && res.data != null){
        this.list = [];
        if(res.data.list!=null) this.list = res.data.list;
        this.totalCnt = res.data.total
      }
      await utils.sleepMs(500)
      utils.hideLoading();
    },    
    async updateInfo(info) {
      utils.showLoading()
      if(info.disable_sieve_list!=undefined ){info.disable_sieve_list = info.disable_sieve_list.join("|")}
      let code = -1;
      let actionName = '';
      let tipText = '';
      let postData = utils.cloneObj(info);
      if (this.handleType==1) {
        actionName = 'add_item';
        tipText = '添加成功！';    
      }else if(this.handleType==2){
        actionName = 'edit_item';
        tipText = '编辑成功！';     
      }else if(this.handleType==-1){
        actionName = 'del_item';
        tipText = '删除成功！';
        postData = {"id":postData.Id};
      }else if(this.handleType==3){
        actionName = 'enable_item';
        tipText = '启用成功！';
        postData = {"id":postData.id};
      }else if(this.handleType==4){
        actionName = 'disable_item';
        tipText = '禁用成功！';
        postData = {"id":postData.id};
      }
      let res = await this.RequestPost(actionName, postData);
      code = res.code;
      if (code == 0) {
        utils.hideFormPage(this.formPopIndex);
        await utils.sleepMs(1000);
        this.onSearchGetList();
        utils.showTip(tipText);
      }
      utils.hideLoading();
    },    
    //添加 编辑用户
    async editInfo(type,row) {
      this.handleType=type;
      let title = "";
      let info = {};
      if(this.handleType==1){
        title = "添加国家";
        info = {
          full_name:"",          
          short_name:"",
          area_code:"",
          number_bit_count:"",
        };
      }else{
          // this.format.id.labelDisabled = true
          this.format.full_name.labelDisabled = true
          this.format.short_name.labelDisabled = true
          // this.format.number_bit_count.labelDisabled = true
          this.format.area_code.labelDisabled = true
        title = "编辑国家";
        info = {
          id:row.id,
          full_name:row.full_name,    
          short_name:row.short_name,
          number_bit_count:row.number_bit_count,      
          area_code:row.area_code,        
          disable_sieve_list:row.disable_sieve_list==0?"": row.disable_sieve_list.split("|").map(Number), //拆解显示对应多选labelMultiple
        };
      }
      this.formPopIndex=await utils.showFormPage(
        { title: title,el:this.$parent.$el,width:700,cancelBtnStatus:0},
        info,
        this.format,
        this.ruleValidate,
        this.updateInfo,
        this.onSelectChange,
      );
    },    
    //删除
    sureDel(item,type) {
       this.handleType = -1;
        utils.shadowModel(
          {
          "title":"删除提示",            
          "icon":require('../../assets/images/peach-svg/Frame 427318277 (1).svg'),
          "modalContent":"确认删除 "+item.full_name+"("+item.short_name+")"+" ?",
          "callBackArgs":{"Id":item.id}},(res)=>{
        let code = res.code;
        if(code==0){
          let data = res.data;
          this.updateInfo(data);
        }
      });
      this.getList()
    },    
    onChangePageSize(page,pageSize){
      this.modal = true        
      this.searchData.page_index = page;
      this.searchData.page_size = pageSize;
      this.getList();
    },
    changeDate(val){
      let num = new Date(val)
      let time = num.getTime()/1000;
      // this.searchData.create_at = time
    },    
    onSelectChange(label,value,reset){
      // this.format.Name.labelValue = []
     
      // if(label=="CompanyId"){
      //   this.isSelectCompany = value
      // }
      // if(label=="DepartmentId"){
      //   this.isSelectDepartment = value
      // }
      // if(label=="GroupId"){
      //   this.isSelectGroup = value
      // }
      // if(label=="Name"){
      //   this.isSelectName = value
      // }
      // if(label=="PurchaseType"){
      //   this.PurchaseType1 = 0
      //   this.PurchaseType2 = 0
      //   this.PurchaseType1 = parseInt(value["0"])
      //   this.PurchaseType2 = parseInt(value["1"])
      // }
      // this.userlist.forEach((item) => {
      //   if(item.Company == this.isSelectCompany && item.Department == this.isSelectDepartment && item.Group == this.isSelectGroup ) {
      //     this.format.Name.labelValue.push({id:item.Id,name:item.Name});
      //   }
      // })
    },    
    slotHeader(h) {
      return [h("div",{class:{"allCount":true},"style":{"margin-left":"10px"}})]
    },
    filterPartner(item){
      if (item.Id == -1) return true;
      if (this.searchData.searchBusinessId == -1 ) return true
        return item.BusinessId==this.searchData.searchBusinessId;
    },
  },
  mounted(){
    bus.$on('sub',res =>{
      bus.$emit('aa',this.list[res])
    })
  }
};
</script>  